<?php
// +----------------------------------------------------------------------
// | Author: Stupboy King
// +----------------------------------------------------------------------
namespace app\api\controller\driver;
use think\Controller;
use think\Config;
use think\Request;
class Base extends Controller
{
    public $driverInfo;
    public $redisPreFix = 'jjcx.driver.';

    /**
     * 初始化 redis 请求
     */
    public function _initialize()
    {
        // Redis缓存
        $this->redis    = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->dtoken   = input('dtoken','');
        $this->requestMethod = Request::instance()->isPost(); //测试期间允许GET方便测试
        $this->dateTime = date('Y-m-d H:i:s');
        list($this->requestStatus,$this->requestMsg) = $this->checkRequest();
    }

    public function setRedis($key,$value){
        $data = is_array($value) ? serialize($value) : $value;
        $this->redis->set($key,$data);
    }

    public function getRedis($key){
        $value    = $this->redis->get($key);
        $jsonData = unserialize($value);
        return (null === $jsonData) ? $value : $jsonData;
    }

    /**
     * 权限验证
     * @param int $code
     * @param string $msg
     */
    public function auth(){
        if($this->requestStatus==0){
            abort(0,$this->getErrorMsg($this->requestMsg));
        }
    }

    /**
     * 请求过滤
    */
    public function checkRequest(){
        if(!$this->requestMethod){
            return [3,103];
        }
        if(empty($this->dtoken)){
            return [0,101];
        }
        $this->driverInfo = $this->getRedis($this->dtoken);
        $arr              = explode('@',$this->dtoken);
        $driverBase       = $arr[0].'*';
        $otherLogin       = $this->redis->keys($driverBase);
        if(empty($this->driverInfo) && !empty($otherLogin)){
            return [0,120];
        }
        if(empty($this->driverInfo) || time() - $this->driverInfo['activetime'] >Config::get('login_time_expire')){
            return [4,301];
        }
        $this->driverInfo['activetime'] = time();
        $this->setRedis($this->dtoken,$this->driverInfo);
        return [1,'ok'];
    }

    /**
     * 成功返回
    */
    public function retSucc($data=array(),$msg='ok',$code=1){
        $info['code'] = $code;
        $info['msg']  = $msg;
        $info['time'] = time();
        $info         = array_merge($info,$data);
        return json($info);
    }

    /**
     * 失败返回
    */
    public function retError($msg='',$code=0){
        $info['code'] = $code;
        $info['msg']  = intval($msg)>99 ? $this->getErrorMsg($msg) : $msg;
        $info['time'] = time();
        return json($info);
    }

    /**
     * 错误信息代码转换
     * @param int $code
     * @return string
     */
    public function getErrorMsg($code=100){
        $errorArr = \think\Config::get('error_msg');
        return isset($errorArr[$code]) ? $errorArr[$code] : 'undefine';
    }

    /**
     * 批量参数获取
     * @param $string
     * @return array
     */
    public function getMassParam($string){
        $ret = [];
        if(empty($string)){
            return [];
        }
        $arr = explode(',',$string);
        foreach ($arr as $v){
            $arr2 = explode('|', $v);
            if(count($arr2)>1){
                $ret[] = input($arr2[0],$arr2[1]);
            }else{
                $ret[] = input($v);
            }
        }
        return $ret;
    }

    /**
     * 图片转base64上传
     * @param $base64_image_content
     * @return array 上传结果
     */
    public function saveBase64($base64_image_content)
    {
        if(empty($base64_image_content)){
            return [0,114];
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            if(!isset($result[2]) || empty($result[2])){
                return [0,118];
            }
            $type = $result[2];
            $new_file = "upload/driver/img/" . date('Ymd', time()) . "/";
            if (!file_exists($new_file)) {
                mkdir($new_file, 0700);
            }
            $new_file = $new_file . md5(uniqid()) . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                return [1, $new_file];
            } else {
                return [0, 115];
            }
        }
    }

    /**
     * upd转发定位GPS数据 swoole处理
     */
    public function udpGet($sendMsg = '')
    {
        $ip     = \think\Config::get('udp_server');
        $port   = \think\Config::get('udp_port');
        $handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr);
        if (!$handle) {
            return [0,$errstr];
        }
        fwrite($handle, $sendMsg . "\n");
        $result = fread($handle, 1024);
        fclose($handle);
        return [1,'ok'];
    }

}
